﻿using Application.Check_hService;
using Domain.Entity.ic;
using Domain.Entity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Application.ProductService;
using Application.PublicFileService;
using Application.PurchaseReturn_dService;
using Application.PurchaseReturn_hService;
using Domain.Entity.ord;
using System.Transactions;
using WMSManage.Filter;
using Application.Check_dService;
using Application.Allot_hService;
using Domain.Entity.tr;

namespace WMSManage.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]//需要鉴权
    public class Check_hController : ControllerBase
    {
        private readonly ICheck_hService check_HService;
        private readonly ICheck_dService check_DService;
        private readonly IPublicFileService publicFileService;

        public Check_hController(ICheck_hService check_HService,ICheck_dService check_DService,IPublicFileService publicFileService)
        {
            this.check_HService = check_HService;
            this.check_DService = check_DService;
            this.publicFileService = publicFileService;
        }


        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="code"></param>
        /// <param name="type"></param>
        /// <param name="status"></param>
        /// <param name="whid"></param>
        /// <param name="CurrentPage"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<FenYe<Check_h>> GetCheck_h(string? code, string? type, int? status, int? whid,int CurrentPage)
        {
            FenYe<Check_h> fenYe = new FenYe<Check_h>
            {
                CurrentPage = CurrentPage,
            };
            return await check_HService.GetCheck_h(fenYe, code, type, status, whid);
        }



        /// <summary>
        /// 高级查询
        /// </summary>
        /// <param name="code"></param>
        /// <param name="startdate"></param>
        /// <param name="enddate"></param>
        /// <param name="status"></param>
        /// <param name="type"></param>
        /// <param name="whid"></param>
        /// <param name="createname"></param>
        /// <param name="startcreatetime"></param>
        /// <param name="endcreatetime"></param>
        /// <param name="approvername"></param>
        /// <param name="startapprovertime"></param>
        /// <param name="endapprovertime"></param>
        /// <param name="inuser"></param>
        /// <param name="CurrentPage"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<FenYe<Check_h>> GetAdvancedCheck_h(string? code, string? startdate, string? enddate, int? status, string? type, int? whid, string? createname, string? startcreatetime, string? endcreatetime, string? approvername, string? startapprovertime, string? endapprovertime, string? inuser, int CurrentPage)
        {
            FenYe<Check_h> fenYe = new FenYe<Check_h>
            {
                CurrentPage = CurrentPage,
            };
            return await check_HService.GetAdvancedCheck_h(fenYe, code, startdate, enddate, status, type, whid, createname, startcreatetime, endcreatetime, approvername, startapprovertime, endapprovertime, inuser);
        }


        /// <summary>
        /// 添加盘点单
        /// </summary>
        /// <param name="payload"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> AddCheck_h(AddCheck_hPayload payload)
        {
            //开启事务
            using var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
            try
            {
                //业务逻辑
                //1.添加主盘点单
                var id = await check_HService.AddCheck_h(payload.checkData);//返回的是当前主键

                //2.添加盘点明细
                foreach (var details in payload.checkDetails)
                {
                    var check_d = new Check_d
                    {
                        ic_id = id,
                        proc_id = details.proc_id,
                        proc_name = details.proc_name,
                        icd_num = details.icd_num,
                        profitandloss_num = details.profitandloss_num,
                        icd_status = details.icd_status,
                        icd_price = details.icd_price,
                        profitandloss_total = details.profitandloss_total,
                        instock_status=details.instock_status,
                        outstock_status = details.outstock_status,
                        remark = details.remark,
                    };
                    await check_DService.AddCheck_d(check_d);
                }

                //3.添加附件
                foreach (var item in payload.attachments)
                {
                    await publicFileService.AddFile(item);
                }
                scope.Complete();//提交事务
                return id; // 返回主入库单ID表示成功
            }
            catch (Exception ex)
            {
                //出错自动回滚
                Console.WriteLine(ex.Message);
                return 0;
            }
        }




        /// <summary>
        /// 根据id查询盘点信息
        /// </summary>
        /// <param name="icid"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Check_h> GetCheck_hById(int icid)
        {
            return await check_HService.GetCheck_hById(icid);
        }



        /// <summary>
        /// 删除盘点单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<int> DeleteCheck_h(int id)
        {
            return await check_HService.DeleteCheck_h(id);
        }



        /// <summary>
        /// 修改盘点单
        /// </summary>
        /// <param name="updateCheck_HPayload"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> UpdateCheck_h(UpdateCheck_hPayload payload)
        {
            // 开启事务
            using var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
            try
            {
                // 1. 修改主盘点单
                await check_HService.UpdateCheck_h(payload.checkData);

                // 2. 修改明细
                // 2.1 获取所有旧明细，并存入字典方便查找
                var oldDetails = await check_DService.GetCheck_Ds(payload.checkData.ic_id);
                var oldDetailsMap = oldDetails.ToDictionary(d => d.icd_id);

                // 2.2 从前端提交的数据中获取到新的明细
                var newDetails = payload.checkDetails;
                var newDetailsIds = newDetails.Where(d => d.icd_id > 0).Select(d => d.icd_id).ToList();

                // 2.3 处理被删除的明细 (ID在旧的不在新的)
                var idsToDelete = oldDetailsMap.Keys.Except(newDetailsIds).ToList();
                if (idsToDelete.Any())
                {
                    foreach (var id in idsToDelete)
                    {
                        // 从数据库删除这条明细
                        await check_DService.DeleteCheck_d(id);
                    }
                }

                // 2.4 遍历所有提交的明细，进行新增或修改
                foreach (var detail in newDetails)
                {
                    if (detail.icd_id > 0) // purtd_id > 0 表示是已存在的项，需要修改
                    {
                        if (oldDetailsMap.TryGetValue(detail.icd_id, out var oldDetail))
                        {
                            // 更新数据库中的明细记录
                            await check_DService.UpdateCheck_d(detail);
                        }
                    }
                    else // purtd_id <= 0 表示是新增的项
                    {
                        detail.ic_id = payload.checkData.ic_id;
                        await check_DService.AddCheck_d(detail);
                    }
                }

                // 3. 修改附件 (先删后增的方式虽然效率不高，但逻辑简单，这里保持不变)
                var filelist = payload.attachments;
                if (filelist != null && filelist.Any())
                {
                    await publicFileService.DeleteFile(filelist[0].business_type, filelist[0].business_code);
                    foreach (var item in filelist)
                    {
                        await publicFileService.AddFile(item);
                    }
                }

                scope.Complete(); // 提交事务
                return 1;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return 0; // 发生异常，事务回滚
            }
        }



        /// <summary>
        /// 查询盘亏的单据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<Check_h>> Getkui()
        {
            return await check_HService.Getkui();
        }


        /// <summary>
        /// 查询盘盈的单据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<Check_h>> Getying()
        {
            return await check_HService.Getying();
        }



        /// <summary>
        /// 盘点汇总数据查
        /// </summary>
        /// <param name="proc_code"></param>
        /// <param name="ic_code"></param>
        /// <param name="ic_type"></param>
        /// <param name="create_name"></param>
        /// <param name="type_id"></param>
        /// <param name="proc_primary_unit"></param>
        /// <param name="wh_id"></param>
        /// <param name="ic_user"></param>
        /// <param name="createstartTime"></param>
        /// <param name="createendTime"></param>
        /// <param name="checkprofitNumMin"></param>
        /// <param name="checkprofitNumMax"></param>
        /// <param name="checklossesNumMin"></param>
        /// <param name="checklossesNumMax"></param>
        /// <param name="checkprofitTotalMin"></param>
        /// <param name="checkprofitTotalMax"></param>
        /// <param name="checklossesTotalMin"></param>
        /// <param name="checklossesTotalMax"></param>
        /// <param name="icStatusArray"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<CheckTotals> Gettotal(
            string? proc_code, string? ic_code, string? ic_type, string? create_name,
            int? type_id, string? proc_primary_unit, int? wh_id, string? ic_user,
            string? createstartTime, string? createendTime,
            decimal? checkprofitNumMin, decimal? checkprofitNumMax,
            decimal? checklossesNumMin, decimal? checklossesNumMax,
            decimal? checkprofitTotalMin, decimal? checkprofitTotalMax,
            decimal? checklossesTotalMin, decimal? checklossesTotalMax,
            [FromQuery] int[]? icStatusArray)
        {
            return await check_HService.Gettotal(
            proc_code, ic_code, ic_type, create_name,
            type_id, proc_primary_unit, wh_id, ic_user,
            createstartTime, createendTime,
            checkprofitNumMin, checkprofitNumMax,
            checklossesNumMin, checklossesNumMax,
            checkprofitTotalMin, checkprofitTotalMax,
            checklossesTotalMin, checklossesTotalMax,
            icStatusArray);
        }



        /// <summary>
        /// 查询货品盘点记录
        /// </summary>
        /// <param name="procid"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<Check_h>> GetByPid(int procid)
        {
            return await check_HService.GetByPid(procid);
        }
    }
}
